import { createRouter, createWebHistory, RouteRecordRaw } from 'vue-router'
import { qiankunWindow } from 'vite-plugin-qiankun/dist/helper'
import HomePage from '../views/HomePage.vue'

// 获取qiankun环境下的基础路由
const getBasePath = () => {
  return qiankunWindow.__POWERED_BY_QIANKUN__ ? '/app2' : '/'
}

// 路由配置
const routes: Array<RouteRecordRaw> = [
  {
    path: '/',
    name: 'home',
    component: HomePage,
    meta: { title: '首页' }
  },
  {
    path: '/dashboard',
    name: 'dashboard',
    component: () => import('../views/DashboardView.vue'),
    meta: { title: '仪表盘' }
  },
  {
    path: '/charts',
    name: 'charts',
    component: () => import('../views/ChartsView.vue'),
    meta: { title: '图表' }
  },
  {
    path: '/report',
    name: 'report',
    component: () => import('../views/ReportView.vue'),
    meta: { title: '报表' }
  }
]

// 创建路由实例
const router = createRouter({
  history: createWebHistory(getBasePath()),
  routes
})

// 路由守卫
router.beforeEach((to, from, next) => {
  // 直接放行所有路由
  next()
})

// 路由切换时自动设置document.title
router.afterEach((to) => {
  const appName = 'app2';
  const baseTitle = '数据可视化系统';
  const pageTitle = to.meta?.title as string || String(to.name || '');
  const fullTitle = pageTitle ? `${pageTitle} - ${baseTitle}` : baseTitle;
  
  // 直接设置document.title，这将在独立运行时生效
  document.title = fullTitle;
  
  // 如果在微前端环境中，通知基座应用
  if (qiankunWindow.__POWERED_BY_QIANKUN__) {
    // 使用自定义事件通知基座应用，实现低耦合通信
    try {
      // 创建自定义事件，包含必要的标题信息
      const titleChangeEvent = new CustomEvent('micro-app-title-change', {
        detail: {
          title: pageTitle,
          fullTitle: fullTitle,
          appName: appName,
          path: to.fullPath
        }
      });
      
      // 在window上派发事件，基座应用可以监听此事件
      window.dispatchEvent(titleChangeEvent);
    } catch (e) {
      console.error('[App2] Failed to dispatch title change event:', e);
    }
  }
})

export default router 